<template>
  <div>
    <el-button type="primary" @click="downLoad">下载</el-button>
    <el-button type="primary" @click="uploadFile">原生上传</el-button>
    <el-progress :percentage="percentage" style="width: 300px"></el-progress>

    <el-upload class="upload-demo" drag action="/upLoadFile" :http-request="upLoad" multiple>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">
        只能上传jpg/png文件，且不超过500kb
      </div>
    </el-upload>

    <div v-show="flag" style="border:1px solid red">
      <Emotion @emotion='getEmotion' />
    </div>
    <div ref="box" id="test" @paste="pastefunction" contenteditable="true" style="height: 200px; width: 400px; border: 1px solid red"></div>
    <el-button type="primary" @click="openFace">表情</el-button>
  </div>
</template>

<script>
import axios from "axios";
import { downLoadFile, uploadFile } from "@/utils/filetools";
export default {
  components: {
    Emotion: () => import('@/components/Emotion')
  },
  data() {
    return {
      percentage: 0,
      src: "",
      uploadFile,
      flag: false
    };
  },
  mounted() { },
  methods: {
    openFace() {
      this.flag = true
    },
    getEmotion(el) {
      var selection = window.getSelection()
      // selection.anchorNode.splitText(selection.anchorNode.after(el))
      document.execCommand("insertHTML", false, el)//返回值boolean代表是否插入成功 //不兼容兼容ie，优化思路通过光标分割进行插入

    },
    //将base64转换为blob
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      var blob = new Blob([u8arr], { type: mime })
      //  return new File([blob], filename, {type:mime});//base64转换为file ie不兼容
      return this.blobToFile(blob, '123');
    },
    //将blob转换为file 貌似也没转换成功
    blobToFile(theBlob, fileName) {
      theBlob.lastModifiedDate = new Date();
      theBlob.name = fileName;
      return theBlob;
    },
    pastefunction(event) {
      if (event.clipboardData || event.originalEvent) {
        event.preventDefault();
        var clipboardData = (event.clipboardData || event.originalEvent.clipboardData);
        // 兼容chorme或hotfire
        var items = clipboardData.items;
        for (var i = 0, len = items.length; i < len; i++) {
          console.log(items[i].type);
          if (items[i].type.indexOf("image") !== -1) {
            var blob = items[i].getAsFile();// 此方法只是living standard firefox ie11 并不支持
            this.upLoad(blob)
            // var reader = new FileReader();
            // reader.onload = (event) => {
            //   //  reader.result//图片的Base64编码字符串
            //   //可以在这里写上传逻辑 直接将base64编码的字符串上传
            //   console.log(blob);
            // }
            // reader.readAsDataURL(blob);
            break;
          } else if (items[i].type.indexOf("text") !== -1) {
            var text = clipboardData.getData("text/plain");//text/html
            console.log(text);
            document.execCommand("insertText", false, text);
            break
          }
        }
      } else {
        //for ie11
        var text = window.clipboardData.getData("text") || "";
        if (text !== "") {//获取粘贴文本
          event.preventDefault ? event.preventDefault() : event.returnValue = false;
          if (window.getSelection) {
            // 针对于ie11 10 9 safari
            var newNode = document.createElement("span");
            newNode.innerHTML = text;
            window.getSelection().getRangeAt(0).insertNode(newNode);
          } else {
            // 兼容ie10 9 8 7 6 5
            document.selection.createRange().pasteHTML(text);
          }
        } else { //获取文件还没完善
          setTimeout(async () => {
            var imgList = document.querySelectorAll('#test img');
            for (let i = 0, len = imgList.length; i < len; i++) {
              // console.log(imgList[i]);//base64格式
              if (imgList[i].className.indexOf('my_img') == -1) {
                var formDate = new FormData()
                var file = this.dataURLtoBlob(imgList[i].src, '123')
                this.upLoad(file)
              }
            }
          }, 1);
        }
      }
    },
    // 下载
    async downLoad(e) {
      const res = await axios.get("/download", {
        onDownloadProgress: (e) => {
          this.percentage = Number(((e.loaded / e.total) * 100).toFixed(0));
        },
        responseType: "blob", //下载文件流必须的，设置后通过content-type可以获取类型
      });
      // var reader = new FileReader();
      // reader.readAsDataURL(res.data);
      // reader.onload = function () {
      //   console.log(reader.result); //获取到base64格式
      // };
      downLoadFile(res.data, "p");
    },
    // 上传
    async upLoad(file) {
      console.log(file.file ? file.file : file);
      let url =
        process.env.NODE_ENV === "production"
          ? "http://121.36.2.1:22222/admin/guest/file/uploadChatFile?creatorId=1002&customerId=1002"
          : "/upLoadFile";
      let FormDatas = new FormData();
      FormDatas.append("file", file.file || file);
      // var reader = new FileReader();
      // reader.readAsDataURL(file.file);
      // reader.onload = function () {
      //   console.log(reader.result); //获取到base64格式
      // };
      let { data } = await axios.post(url, FormDatas, {
        onUploadProgress: (e) => {
          this.percentage = Number(((e.loaded / e.total) * 100).toFixed(0));
        },
      });
      document.execCommand("insertHtml", false, `<img src="${data.data.path}" alt="" style="width:80px;height:80px" >`);
    },
  },
};
</script>

<style lang="scss">
#test {
  line-height: 24px;
  img {
    vertical-align: middle;
  }
}
</style>
